package com.itrus.contract.extension.shardinsphere.algorithm;


import com.itrus.contract.extension.shardinsphere.enumeration.TableRulesEnum;
import com.itrus.contract.extension.shardinsphere.util.ShardingDateValueUtil;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.Collection;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

public class YearShardingAlgorithm implements StandardShardingAlgorithm<Integer> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Integer> shardingValue) {
        String targetTable = shardingValue.getLogicTableName()+"_"+ ShardingDateValueUtil.getPostfix(shardingValue.getValue(), TableRulesEnum.YEAR);
        if (availableTargetNames.contains(targetTable)){
            return targetTable;
        }
        throw new UnsupportedOperationException("年分片无效的表名称："+targetTable);
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Integer> shardingValue) {
        List<String> postfixList = ShardingDateValueUtil.calcPostfixList(shardingValue.getValueRange().lowerEndpoint()
                        , shardingValue.getValueRange().upperEndpoint(), TableRulesEnum.YEAR)
                .stream().map(o->shardingValue.getLogicTableName()+"_"+o).collect(Collectors.toList());

        return availableTargetNames.stream().filter(a->postfixList.contains(a)).distinct().collect(Collectors.toList());
    }


    @Override
    public String getType() {
        return String.valueOf(TableRulesEnum.YEAR.getIndex());
    }

    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }
}
